from backend.database import engine
from backend.models import User
from backend.auth import AuthHandler
from sqlalchemy.orm import sessionmaker

# 创建会话
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

def reset_user_password(username: str, new_password: str):
    """重置用户密码"""
    db = SessionLocal()
    try:
        # 查找用户
        user = db.query(User).filter(User.username == username).first()
        if not user:
            print(f"用户 {username} 不存在")
            return
        
        # 生成新的密码哈希
        new_hash = AuthHandler.get_password_hash(new_password)
        
        # 更新密码
        user.password_hash = new_hash
        db.commit()
        db.refresh(user)
        
        print(f"用户 {username} 的密码已成功重置为: {new_password}")
        print(f"新的密码哈希: {new_hash}")
        return True
    except Exception as e:
        print(f"重置密码时出错: {e}")
        db.rollback()
        return False
    finally:
        db.close()

if __name__ == "__main__":
    reset_user_password("testuser", "password123")